package cn.lvji.sus;

import cn.lvji.sus.redis.RedisUtils;
import org.slf4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * 配置文件
 *
 * @author zhouzx
 */
public class Config {
    private static final Logger logger = getLogger(Config.class);

    private static Properties properties;
    private static final List<String> VALIDATE_KEYS = Arrays.asList(
            "db.url", "db.username", "db.password",
            "db.idle.timeout", "db.max.poolsize", "db.min.idle",
            "db.max.lifetime", "db.connection.timeout");

    static {
        properties = new Properties();
        InputStream in = RedisUtils.class.getClassLoader().getResourceAsStream("sus.properties");
        try {
            properties.load(in);
            VALIDATE_KEYS.forEach(Config::validate);
        } catch (IOException e) {
            logger.error("read config error!", e);
        }
    }

    public static String getConfig(String key) {
        return properties.getProperty(key);
    }

    public static Long getLongConfig(String key) {
        try {
            return Long.parseLong(properties.getProperty(key));
        } catch (Exception e) {
            return null;
        }
    }

    public static Integer getIntConfig(String key) {
        try {
            return Integer.parseInt(properties.getProperty(key));
        } catch (Exception e) {
            return null;
        }
    }

    private static void validate(String key) throws IllegalAccessError {
        if (getConfig(key) == null) {
            throw new IllegalAccessError(key + "必须配置！");
        }
    }
}
